package com.gitee.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.bo.RolePermissionBo;
import com.gitee.mapper.RolePermissionMapper;
import com.gitee.pojo.RolePermission;
import com.gitee.service.IRolePermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements IRolePermissionService {

    /**
     * 根据角色id删除关联权限
     * @param roleId
     * @return
     */
    @Transactional
    @Override
    public Boolean deleteByRoleId(Integer roleId) {
        LambdaUpdateWrapper<RolePermission> updateWrapper = new UpdateWrapper<RolePermission>()
                .lambda().eq(RolePermission::getRoleId, roleId);
        return super.remove(updateWrapper);
    }

    /**
     * 根据角色id查询关联权限id
     *
     * @param roleId
     * @return
     */
    @Override
    public List<Integer> listByRoleId(Integer roleId) {
        LambdaQueryWrapper<RolePermission> queryWrapper = new QueryWrapper<RolePermission>().lambda().eq(RolePermission::getRoleId, roleId);
        List<RolePermission> rolePermissions = super.list(queryWrapper);
        return rolePermissions.stream().map(RolePermission::getPermissionId).collect(Collectors.toList());
    }

    /**
     * 根据角色id更新权限
     *
     * @param roleId
     * @param rolePermissionBo
     * @return
     */
    @Transactional
    @Override
    public Boolean updateByRoleId(Integer roleId, RolePermissionBo rolePermissionBo) {
        deleteByRoleId(roleId);
        List<RolePermission> rolePermissions = rolePermissionBo.getPermissionIds().stream().map(permissionId -> {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            return rolePermission;
        }).collect(Collectors.toList());
        return super.saveBatch(rolePermissions);
    }
}
